package com.webserver.controller;

import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;
import com.webserver.vo.User;
import com.webserver.vo.Write;

import java.io.*;

/**
 * 用于处理与用户数据相关的操作
 */
public class UserController {
    //所有用户信息所保存的目录
    public static final String USER_DIR = "./users/";
    public static final String WRITE_DIR = "./write/";

    static {
        File dir = new File(USER_DIR);
        if (!dir.exists()) {//如果该目录不存在则自动创建
            dir.mkdirs();
        }


    }
    static {
        File dirs = new File(WRITE_DIR);
        if (!dirs.exists()) {//如果该目录不存在则自动创建
            dirs.mkdirs();
        }
    }


//    public void login(HttpServletRequest request, HttpServletResponse response) {
//        System.out.println("开始处理用户登录...");
//        String username = request.getParameter("username");//和输入框name属性值要一致
//        String password = request.getParameter("password");
//        System.out.println(username + "," + password);
//
//        if (username == null || password == null) {
//            File file = new File("./webapps/myweb/login_error.html");
//            response.setEntity(file);
//            return;
//        }
//        try (FileInputStream fis = new FileInputStream(USER_DIR + username + ".obj");
//             ObjectInputStream ois = new ObjectInputStream(fis)) {
//            User p = (User) ois.readObject();
//            System.out.println(p);
//            if (p.getUsername().equals(username) && p.getPassword().equals(password)) {
//                File file = new File("./webapps/myweb/login_success.html");
//                response.setEntity(file);
//            } else {
//                File file = new File("./webapps/myweb/login_fail.html");
//                response.setEntity(file);
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        } catch (ClassNotFoundException e) {
//            e.printStackTrace();
//        }
//
//
//        System.out.println("用户登录处理完毕!");
//    }

    /**
     * 处理用户注册操作
     *
     * @param request  请求对象
     * @param response 响应对象
     */
    public void reg(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("开始处理用户注册...");
        /*
            1:通过request对象获取reg.html上表单提交的用户数据
            2:将该用户信息保存
            3:设置response对象给用户响应注册结果页面
         */
        //1
        /*
            通过请求对象的方法getParameter获取注册页面表单中某个输入框的值。
            需要注意，该方法传递的参数必须与页面表单中该输入框name属性执行的值一致!
         */
        //对应注册页面用户名输入框:<input name="username" type="text">
        String username = request.getParameter("username");//和输入框name属性值要一致
        String password = request.getParameter("password");
        String nickname = request.getParameter("nickname");
        String ageStr = request.getParameter("age");
        System.out.println(username + "," + password + "," + nickname + "," + ageStr);
        /*
            必要的数据验证:
            要求用户名,密码,昵称,年龄不能为空,并且年龄这个字符串表示的必须是一个整数
            否则直接向response中设置一个错误页面:reg_info_err.html
            该页面居中显示一行字:注册信息输入有误,请重新注册
         */

        if (username == null || password == null || nickname == null || ageStr == null || !ageStr.matches("[1-9][0-9]")) {
            File file = new File("./webapps/myweb/reg_fail.html");
            response.setEntity(file);
            return;
        }

        File userFile = new File(USER_DIR + username + ".obj");
        if (userFile.exists()) {
            File file = new File("./webapps/myweb/reg_have.html");
            response.setEntity(file);
            return;
        }


        int age = Integer.parseInt(ageStr);//将年龄转换为int值
        /*
            2
            将该用户信息取名为:用户名.obj写入到该文件中。
            将用户信息以User对象形式表示，并将其序列化到文件里。
         */
        User user = new User(username, password, nickname, age);
        try (
                //                                          ./users/fancq.obj
                FileOutputStream fos = new FileOutputStream(userFile);
                ObjectOutputStream oos = new ObjectOutputStream(fos);
        ) {
            oos.writeObject(user);
            //3设置响应对象发送注册成功页面
            File file = new File("./webapps/myweb/reg_success.html");
            response.setEntity(file);
        } catch (IOException e) {
            e.printStackTrace();
        }


        System.out.println("用户注册处理完毕!");
    }

    /**
     * 用户登录
     *
     * @param request
     * @param response
     */
    public void login(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("开始处理登录...");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        if (username == null || password == null) {
            File file = new File("./webapps/myweb/login_error.html");
            response.setEntity(file);
            return;
        }

        File userFile = new File(USER_DIR + username + ".obj");
        if (userFile.exists()) {//文件存在说明该用户存在
            //反序列化读取该用户信息
            try (
                    FileInputStream fis = new FileInputStream(userFile);
                    ObjectInputStream ois = new ObjectInputStream(fis);
            ) {
                User user = (User) ois.readObject();
                //比较密码
                if (password.equals(user.getPassword())) {
                    //密码一致则登录成功
                    File file = new File("./webapps/myweb/login_success.html");
                    response.setEntity(file);
                    return;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        //设置登录失败
        File file = new File("./webapps/myweb/login_fail.html");
        response.setEntity(file);

        System.out.println("处理登录完毕!");
    }

    public void write(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("开始处理提交...");
        String title = request.getParameter("title");
        String author = request.getParameter("author");
        String content = request.getParameter("content");
        if (title == null || author == null) {
            File file = new File("./webapps/myweb/write_fail.html");
            response.setEntity(file);
            return;
        }
        if (content == null) {
            File file = new File("./webapps/myweb/write_err.html");
            response.setEntity(file);
            return;
        }
        Write write = new Write(title, author, content);
        try (FileOutputStream fos = new FileOutputStream(WRITE_DIR + author + ".obj");
             ObjectOutputStream oos = new ObjectOutputStream(fos)) {
            oos.writeObject(write);
            File file = new File("./webapps/myweb/write_success.html");
            response.setEntity(file);
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("文章提交成功!");
    }
    public void watch(HttpServletRequest request,HttpServletResponse response){
        System.out.println("开始处理查看...");
        String autohr = request.getParameter("author");
        if (autohr==null){
            File file =new File("./webapps/myweb/watch_fail");
            response.setEntity(file);
            return;
        }
        File write = new File(WRITE_DIR+autohr+".obj");
        if (write.exists()){
            try(FileInputStream fis = new FileInputStream(write);
                ObjectInputStream ois = new ObjectInputStream(fis)) {
                Write writeuser = (Write)ois.readObject();
                System.out.println(writeuser);
                File file = new File("./webapps/myweb/watch_success.html");
                response.setEntity(file);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }

        System.out.println("查看成功!");
    }
}
